package com.qyhl.webtv.module_user.setting;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.gyf.immersionbar.ImmersionBar;
import com.library.OnPopupItemClickListener;
import com.library.PopupView;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCacheUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.VersionBean;
import com.qyhl.webtv.commonlib.entity.config.AppConfigBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.UpdateAPK;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.push.PushTools;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_user.R;
import com.qyhl.webtv.module_user.R2;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.leancloud.chatkit.LCChatKit;
import es.dmoral.toasty.Toasty;


/**
 * Created by qyhl on 2017/12/5.
 *
 * @author cookie_zj
 * 设置界面
 */
@Route(path = ARouterPathConstant.SETTING)
public class SettingActivity extends BaseActivity {
    @BindView(R2.id.cache_size)
    TextView cacheSize;
    @BindView(R2.id.version_name)
    TextView mVersionName;
    @BindView(R2.id.clear)
    RelativeLayout clear;
    @BindView(R2.id.unlogin)
    Button unlogin;
    @BindView(R2.id.shield_list)
    RelativeLayout shieldList;
    @BindView(R2.id.check_version)
    RelativeLayout check_version;
    @BindView(R2.id.user_my_home)
    RelativeLayout user_my_home;
    @BindView(R2.id.brightness)
    SeekBar brightness;
    @BindView(R2.id.wifiload)
    Switch wifiload;
    @BindView(R2.id.checkoutNew)
    TextView checkoutNew;
    @BindView(R2.id.popup)
    PopupView popup;
    @BindView(R2.id.back_btn)
    ImageView backBtn;
    @BindView(R2.id.user_setting_text)
    TextView userSettingText;
    @BindView(R2.id.user_my_privacy)
    RelativeLayout user_my_privacy;

    @BindView(R2.id.cancel)
    TextView cancel;

    private LoadingDialog.Builder builder;
    private boolean hasCircle;
    private UpdateAPK updateAPK;
    private boolean brightnessEnable = true;
    private int mVersionCode;

    private final Handler handler = new MyHandler(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.login_activity_setting;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
    }


    private void goPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, 0);
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        updateAPK = new UpdateAPK(this, true).setListener(new UpdateAPK.OnStateListener() {
            @Override
            public void onState(String msg) {
                Toasty.normal(SettingActivity.this, msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void getData(VersionBean.DataBean bean) {
                CommonUtils.getInstance().putConfigData(AppConfigConstant.VERSION_BEAN, bean);
            }
        });


        builder = new LoadingDialog.Builder(SettingActivity.this);
        builder.setTitle("清理中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        //没有爆料不显示爆料关注和我的爆料
        AppConfigBean bean = Hawk.get("config");
        List<AppConfigBean.tabMenus> tabMenusLists = bean.getTabMenus();
        for (int i = 0; i < tabMenusLists.size(); i++) {
            if (tabMenusLists.get(i).getTypeId() == 17) {
                hasCircle = true;
            }
        }

        if (hasCircle) {
            shieldList.setVisibility(View.VISIBLE);
        } else {
            shieldList.setVisibility(View.GONE);
        }

        //点击水波纹效果
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            clear.setBackgroundResource(R.drawable.center_item_ripple);
            shieldList.setBackgroundResource(R.drawable.center_item_ripple);
            user_my_home.setBackgroundResource(R.drawable.center_item_ripple);
            check_version.setBackgroundResource(R.drawable.center_item_ripple);
            user_my_privacy.setBackgroundResource(R.drawable.center_item_ripple);
        }

        //显示缓存大小
        if (StringUtils.isEmpty(GlideCacheUtils.getInstance().getCacheSize(this))) {
            cacheSize.setVisibility(View.GONE);
        } else {
            cacheSize.setText("缓存大小：" + GlideCacheUtils.getInstance().getCacheSize(this));
        }

        //第一次进入是否已登录
        String userName = CommonUtils.getInstance().getUserName();
        if (StringUtils.isNotEmpty(userName) && Hawk.contains("login")) {
            unlogin.setVisibility(View.VISIBLE);
            cancel.setVisibility(View.VISIBLE);
        } else {
            unlogin.setVisibility(View.GONE);
            cancel.setVisibility(View.GONE);
        }
        //获取当前版本号
        try {
            PackageManager manager = getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            mVersionName.setText("当前版本V" + info.versionName);
            mVersionCode = info.versionCode;
            VersionBean.DataBean versionBean = CommonUtils.getInstance().getVersionData();
            if (versionBean != null && (mVersionCode < versionBean.getCode())) {
                checkoutNew.setVisibility(View.VISIBLE);
            }
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        brightness.setProgress(getScreenBrightness());

        wifiload.setChecked(SpfManager.getInstance(this).getBoolean("noPicture", false));

        popup.setPostion(SpfManager.getInstance(this).getInt("fontSize", 2));

    }

    /**
     * 监听
     *
     * @param view
     */
    @OnClick({R2.id.check_version, R2.id.user_my_home, R2.id.user_my_privacy, R2.id.user_rule, R2.id.sdk_list})
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.check_version) {
            checkVersion();

        } else if (i == R.id.user_my_home) {
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        RouterManager.router(ARouterPathConstant.USERINFO);
                    } else {
                        Toasty.normal(SettingActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                        RouterManager.routerLogin(SettingActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {
                    Toasty.normal(SettingActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                    RouterManager.routerLogin(SettingActivity.this, 0);
                }
            });

        } else if (i == R.id.user_my_privacy) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "隐私条款");
            bundle.putString("url", CommonUtils.getInstance().getPrivacyUrl());
            bundle.putBoolean("hasShare", false);
            RouterManager.router(ARouterPathConstant.ADV, bundle);
        } else if (i == R.id.user_rule) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "用户协议");
            bundle.putString("url", "http://vod.136.i2863.com/customerUse.html");
            bundle.putBoolean("hasShare", false);
            RouterManager.router(ARouterPathConstant.ADV, bundle);
        } else if (i == R.id.sdk_list) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "第三方SDK列表");
            bundle.putString("url", CommonUtils.getInstance().getSdkListUrl());
            bundle.putBoolean("hasShare", false);
            RouterManager.router(ARouterPathConstant.ADV, bundle);
        }
    }

    private void checkVersion() {
        VersionBean.DataBean versionBean = CommonUtils.getInstance().getVersionData();
        if (versionBean != null) {
            updateAPK.versionSuccess(versionBean);
        } else {
            updateAPK.checkUpdate();
        }
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //清除缓存
        clear.setOnClickListener(v -> new CommonDialog.Builder(SettingActivity.this)
                .setTitle("提示", R.color.global_black_lv1)
                .setMessage("是否要清除缓存，将会造成首次加载偏慢哟！", R.color.global_black_lv2)
                .setPositiveButton("确定", v1 -> {
                    builder.show();
                    GlideCacheUtils.getInstance().clearImageAllCache(SettingActivity.this);
                    clearCookie();
                    handler.sendEmptyMessageDelayed(0, 1500);
                }, R.color.global_base)
                .setNegativeButton("取消", null, R.color.global_gray_lv2).show());

        /**
         *好友屏蔽列表
         */
        shieldList.setOnClickListener(v -> CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                if (isLogin) {
                    RouterManager.router(ARouterPathConstant.CIRCLE_SHIELD);
                } else {
                    Toasty.normal(SettingActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                    RouterManager.routerLogin(SettingActivity.this, 0);
                }
            }

            @Override
            public void error(String s) {
                Toasty.normal(SettingActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                RouterManager.routerLogin(SettingActivity.this, 0);
            }
        }));

        backBtn.setOnClickListener(v -> finish());

        //注销
        unlogin.setOnClickListener(v -> new CommonDialog.Builder(SettingActivity.this)
                .setTitle("注销", R.color.global_black_lv1)
                .setMessage("确定要退出该账号！", R.color.global_black_lv2)
                .setPositiveButton("确定", v12 -> {
                    if (Hawk.contains("token")) {
                        Hawk.delete("token");
                    }

                    if (Hawk.contains("login")) {
                        Hawk.delete("login");
                    }
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.NICK_NAME, "");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.LOGIN_TOKEN, "");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.USER_NAME, "");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.INVITE_CODE, "");
                    //解绑推送账号
                    PushTools.unBindAccount();
                    BusFactory.getBus().postSticky(new Event.LoginMessage(false));
                    Toasty.normal(SettingActivity.this, "退出成功！").show();
                    unlogin.setVisibility(View.GONE);
                    if (LCChatKit.getInstance().getClient() != null) {
                        LCChatKit.getInstance().close(new AVIMClientCallback() {
                            @Override
                            public void done(AVIMClient avimClient, AVIMException e) {
                            }
                        });
                    }
                    finish();
                }, R.color.global_base)
                .setNegativeButton("取消", null, R.color.global_gray_lv2).show());

        //非wifi无图浏览开关监听
        wifiload.setOnCheckedChangeListener((compoundButton, b) -> SpfManager.getInstance(SettingActivity.this).putBoolean("noPicture", b));

        brightness.setOnTouchListener((v, event) -> {
            if (brightnessEnable) {
                brightnessEnable = false;
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.System.canWrite(SettingActivity.this)) {
                            CommonDialog.Builder builder = new CommonDialog.Builder(SettingActivity.this);
                            builder.setTitle("提示", R.color.global_black_lv1)
                                    .setMessage("打开系统权限才能全局生效，是否去打开？", R.color.global_black_lv2)
                                    .setPositiveButton("去打开", v13 -> goPermission(), R.color.global_base).show();
                            return true;
                        }
                    }
                }
            }
            return false;
        });

        //亮度拖动
        brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (getScreenMode() == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                    setScreenMode(Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                }
                setLight(i);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //字号选择监听

        popup.setOnItemClickListener(new OnPopupItemClickListener() {
            @Override
            public void onItemClickListener(int i, int position, String s) {
                SpfManager.getInstance(SettingActivity.this).putInt("fontSize", position);
            }
        });
        //注销账号
        cancel.setOnClickListener(v -> RouterManager.router(ARouterPathConstant.USER_CANCEL_TIP));
    }

    /**
     * 设置亮度
     */
    private void setLight(int brightness) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = brightness * (1f / 255f);
        getWindow().setAttributes(lp);
        try {
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
            Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
            getContentResolver().notifyChange(uri, null);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    private int getScreenBrightness() {
        int screenBrightness;
        try {
            screenBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception localException) {
            screenBrightness = 0;
        }
        return screenBrightness;
    }

    private int getScreenMode() {
        int screenMode = 0;
        try {
            screenMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
        return screenMode;
    }

    /**
     * 设置当前屏幕亮度的模式
     * SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0  为手动调节屏幕亮度
     */
    private void setScreenMode(int paramInt) {
        try {
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, paramInt);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                unlogin.setVisibility(View.VISIBLE);
                cancel.setVisibility(View.VISIBLE);
            } else {
                unlogin.setVisibility(View.GONE);
                cancel.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("设置");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.SETTING);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("设置");
        MobclickAgent.onPause(this);
        ActionLogUtils.getInstance().onPause(this, ActionConstant.SETTING);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }


    private static class MyHandler extends Handler {
        private final WeakReference<SettingActivity> mActivity;

        public MyHandler(SettingActivity activity) {
            mActivity = new WeakReference<SettingActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SettingActivity settingActivity = mActivity.get();
            switch (msg.what) {
                case 0:
                    if (StringUtils.isEmpty(GlideCacheUtils.getInstance().getCacheSize(settingActivity))) {
                        settingActivity.cacheSize.setText("缓存大小：0");
                    } else {
                        settingActivity.cacheSize.setText("缓存大小：" + GlideCacheUtils.getInstance().getCacheSize(settingActivity));
                    }
                    settingActivity.builder.dismiss();
                    break;
                default:
                    break;
            }
        }
    }

    private void clearCookie() {
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除
        CookieSyncManager.getInstance().sync();
    }

}
